package com.leoman.utils;

import com.leoman.barrage.entity.Barrage;
import com.leoman.entity.Configue;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;

/**
 * Created by Administrator on 2016/9/4 0004.
 */
public class XmlUtil {

    private static Document document;

    public static void init() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 生成xml文件
     *
     * @param fileName
     */
    public static void createXml(String fileName, List<Barrage> barrageList) {
        Element root = document.createElement("i");
        document.appendChild(root);
        Element chatserver = document.createElement("chatserver");
        chatserver.appendChild(document.createTextNode("chat.bilibili.com"));
        Element chatid = document.createElement("chatid");
        chatid.appendChild(document.createTextNode("2962351"));
        Element mission = document.createElement("mission");
        mission.appendChild(document.createTextNode("0"));
        Element maxlimit = document.createElement("maxlimit");
        maxlimit.appendChild(document.createTextNode("1500"));
        Element source1 = document.createElement("source");
        source1.appendChild(document.createTextNode("k-v"));
        root.appendChild(chatserver);
        root.appendChild(chatid);
        root.appendChild(mission);
        root.appendChild(maxlimit);
        root.appendChild(source1);

        // 循环生成弹幕内容
        Element d = null;
        for (Barrage barrage : barrageList) {
            d = document.createElement("d");
            d.setAttribute("p", barrage.getTime().floatValue() + ",1,16" + "," + (barrage.getUserInfo().getIsCreator() == 1 ? "16711680" : "16777215") + ",1422200985,0,D4c73761,757075551");
            d.appendChild(document.createTextNode(barrage.getContent()));
            root.appendChild(d);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");//增加换行缩进，但此时缩进默认为0
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");//设置缩进为2

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
            StreamResult result = new StreamResult(outputStreamWriter);
            transformer.transform(source, result);

            System.out.println("生成XML文件成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void saveFile(String file, String data, boolean append) throws IOException {
        BufferedWriter bw = null;
        OutputStreamWriter osw = null;

        File f = new File(file);
        FileOutputStream fos = new FileOutputStream(f, append);
        try {
            // write UTF8 BOM mark if file is empty
            if (f.length() < 1) {
                final byte[] bom = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
                fos.write(bom);
            }

            osw = new OutputStreamWriter(fos, "UTF-8");
            bw = new BufferedWriter(osw);
            if (data != null) bw.write(data);
        } catch (IOException ex) {
            throw ex;
        } finally {
            try {
                bw.close();
                fos.close();
            } catch (Exception ex) {
            }
        }
    }

    /**
     * 解析xml文件
     *
     * @param fileName
     */
    public static void parserXml(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(fileName);

            NodeList employees = document.getChildNodes();
            for (int i = 0; i < employees.getLength(); i++) {
                Node employee = employees.item(i);
                NodeList employeeInfo = employee.getChildNodes();
                for (int j = 0; j < employeeInfo.getLength(); j++) {
                    Node node = employeeInfo.item(j);
                    NodeList employeeMeta = node.getChildNodes();
                    for (int k = 0; k < employeeMeta.getLength(); k++) {
                        System.out.println(employeeMeta.item(k).getNodeName()
                                + ":" + employeeMeta.item(k).getTextContent());
                    }
                }
            }
            System.out.println("解析完毕");
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        } catch (SAXException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public static String productXml(String path, List<Barrage> barrageList) {
        init();
        createXml(Configue.getUploadPath() + path, barrageList);
        return path;
    }
}
